import axios, { AxiosInstance,Method, AxiosRequestConfig, AxiosResponse, AxiosError, AxiosRequestHeaders } from 'axios'

export default class Axios {
    public http: AxiosInstance
    public that: Axios | null = null
    constructor(config: AxiosRequestConfig) {
        this.http = axios.create(config)
        this.init()
    }
    init() {
        this.http.interceptors.request.use((config: AxiosRequestConfig) => {
            let token: string | null =  localStorage.getItem('token') || null
            let headers: any = config.headers
            if (token != null) {
                headers['token'] = token
            }
            return config
        }, (err: AxiosError) => {
            console.log(err, "错误")
            return Promise.reject(err)
        })
        this.http.interceptors.response.use((response: AxiosResponse) => {
            return Promise.resolve(response.data)
        }, (err: AxiosError) => {
            console.log(err, "错误")
            return Promise.reject(err)
        })
    }
    public fetch(url:string,data:any = {}, method:Method ,headers:AxiosRequestHeaders = {}){
        return this.http.request({
            url,
            method,
            data,
            headers
        })
    }
    get(url:string,params:any = {},headers:AxiosRequestHeaders = {}){
        return this.http.get(url,{params,headers})
    }
    post(url:string,data:any = {}, headers:AxiosRequestHeaders = {}){
        return this.fetch(url,data,"POST",headers)
    }
    delete(url:string,data:any = {}, headers:AxiosRequestHeaders = {}){
        return this.fetch(url,data,"DELETE",headers)
    }
    put(url:string,data:any = {},headers:AxiosRequestHeaders = {}){
        return this.fetch(url,data,"PUT",headers)
    }
}